﻿using System;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Collections.Generic;
using ElectronicWMSA.T_WMS.T_PutOut;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;
using WMSABL;

namespace ElectronicWMSA.Warehouse
{
    public partial class List_VersionPKNOFrm : Form
    {
        private string _IP = "";
        public List_VersionPKNOFrm()
        {
            InitializeComponent();

            this.pageControl1.PageCurrent = 1;
            this.pageControl1.PageSize = 100;
            _IP = WMSADBUtility.Database.ConnString;
        }

        private string strWhere_PKNO = "";
        private int DBindData_PKNO()
        {
            Comm.Forms.MsControls.PageData pageData = new Comm.Forms.MsControls.PageData();
            pageData.TableName = "Vlh_Version_PickNoInfo";
            pageData.PrimaryKey = "PKNO";
            pageData.OrderStr = "PKNO";
            pageData.PageIndex = this.pageControl1.PageCurrent;
            pageData.PageSize = this.pageControl1.PageSize;
            pageData.QueryCondition = strWhere_PKNO;
            pageData.QueryFieldName = "*";

            WaitingBoxFrm wf = new WaitingBoxFrm((obj, args) => { Thread.Sleep(500); pageData.QueryDataTable(); }, 1200); wf.ShowDialog(this);

            this.pageControl1.bindingSource.DataSource = pageData.dsInfo.Tables[0];
            this.pageControl1.bindingNavigator.BindingSource = pageControl1.bindingSource;

            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = this.pageControl1.bindingSource;
            this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dataGridView1.MergeColumnNames.Add("PKNO1");
            this.dataGridView1.MergeColumnNames.Add("PONO1");
            this.dataGridView1.MergeColumnNames.Add("ProductModel1");
            this.dataGridView1.MergeColumnNames.Add("Qty1");
            //this.dataGridView1.MergeColumnNames.Add("VersionNO1");
            //this.dataGridView1.MergeColumnNames.Add("VersionCount1");
            this.dataGridView1.ClearSelection();
            return pageData.TotalCount;
        }
        private int pageControl1_EventPaging(Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindData_PKNO();
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);

        }

        private void btnPicking_Search_Click(object sender, EventArgs e)
        {
            strWhere_PKNO = " 1=1 ";
            if (!string.IsNullOrEmpty(txt_pick.Text.Trim()))
            {
                this.strWhere_PKNO += "   AND [PKNO] = '" + txt_pick.Text.Trim() + "'";
            }
            this.pageControl1.Bind();
        }
        private void btn_ExportPKNOInfo_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (MessageClass.enquire("确认导出？") == DialogResult.OK)
                {
                    DataTable dt;
                    string SelectSQL = "SELECT [PKNO] AS 装箱单号,[PONO] AS PO号,[Destination] AS 目的地,[OutDate] AS 出厂日期,[ProductModel] AS 机种,[Qty] AS 机种总数,[VersionNO] AS 机种版本号,[VersionCount] AS 机种版本号汇总数,[BoardNO] AS 板号 FROM [DB_WMSFIRST].[dbo].[Vlh_Version_PickNoInfo] ";
                    if (strWhere_PKNO != "")
                    {
                        SelectSQL += " WHERE " + strWhere_PKNO + " ";
                    }
                    SelectSQL += "  ORDER BY PKNO,PONO,Destination,ProductModel,VersionNO ";
                    dt = SYDZ.WMS.DBUtility.DbHelperSQL.ExecuteDataTable(SelectSQL);
                    ExPut.GetNopiExcel(dt);
                }
            }
            else
            {
                MessageClass.warning("请先查询数据！");
            }
        }
        private void btnpop_Click(object sender, EventArgs e)
        {
            versionCount_Product = 0;
            ds_01_StoreVersion = public_DS.GetDataSet_01_WMS("");
            versionCount_Product = ds_01_StoreVersion.Tables[0].Rows.Count;
            if (versionCount_Product > 0)
            {
                if (MessageClass.enquire("部分机种未同步数据，是否继续装订单导入？") == DialogResult.OK)
                {
                    PickingVersionFrm frm = new PickingVersionFrm();
                    frm.ShowDialog();
                }
            }
            else
            {
                PickingVersionFrm frm = new PickingVersionFrm();
                frm.ShowDialog();
            }

        }

        #region 更新版本号
        private void btn_SetVersion_Click(object sender, EventArgs e)
        {
            // 第 1 步 提取空版本号机种
            versionCount_Product = 0;// 总数量 
            ds_01_StoreVersion = public_DS.GetDataSet_01_WMS("");
            versionCount_Product = ds_01_StoreVersion.Tables[0].Rows.Count;

            if (versionCount_Product > 0)
            {
                if (MessageClass.enquire("[" + versionCount_Product + "]-021" + "确认同步数据？") == DialogResult.OK)
                {
                    WaitinglodingFrm wf = new WaitinglodingFrm((obj, args) => { Thread.Sleep(500); SetProductModelVison(); }, 50000); wf.ShowDialog(this);
                }
                SystemVariable.AddLogInfo("版本管理-同步数据", "用户：【" + SystemVariable.Login_Name + "】操作了版本管理同步数据。");
            }
            if (Message_Str != "")
            {
                MessageClass.right(Message_Str);
            }
            if (P_Machine_ListStrDefault != "")
            {
                SystemVariable.AddLogInfo("版本管理-同步数据", "用户：【" + SystemVariable.Login_Name + " 同步数据时-默认版本号机种信息：" + P_Machine_ListStrDefault);
            }
            if (P_Machine_ListStr != "")
            {
                SystemVariable.AddLogInfo("版本管理-同步数据", "用户：【" + SystemVariable.Login_Name + " 同步数据时-未完成同步数据信息：" + P_Machine_ListStr);
            }
        }

        PublicDataSet public_DS = new PublicDataSet();
        private string P_Machine = "";       // 生产机种
        private string T_Machine = "";       // T字机种
        private string _Serial_Number = "";  // 机种序列号
        private string _MovementNO = "";     // 机芯号
        private string _CheckTime = "";      // 配料单号确认时间
        private string _ProductNO_BOM = "";  // BOM部品号
        private string _PKNO_Time = "";      // 制单时间(判定版本号)
        private string _SetVersionNo = "";   // 版本号
        private int versionCount_Product = 0;// 总数量    
        private int versionCount_Producted = 0;// 实际调整数量    
        DataSet ds_01_StoreVersion = new DataSet();

        private string Message_Str = "";
        private string P_Machine_ListStr = "";        //无版本管理机种列表
        private string P_Machine_ListStrDefault = ""; //默认版本号
        private void SetProductModelVison()
        {
            try
            {
                string _UpdateStarTime1 = DateTime.Now.ToString();
                bool VersionFalg = false; //判断是否有版本管理
                List<string> list = new List<string>();
                if (versionCount_Product > 0)
                {
                    string _Machine_WMS = ""; // 成品仓机种
                    string _Machine_Type = "";
                    P_Machine_ListStr = "";
                    P_Machine_ListStrDefault = "";
                    Message_Str = "";
                    for (int i = 0; i < versionCount_Product; i++)   // 赋值版本号
                    {
                        P_Machine = "";
                        T_Machine = "";
                        _Serial_Number = "";
                        _SetVersionNo = "";
                        _CheckTime = "";
                        _PKNO_Time = "";

                        _Machine_WMS = ds_01_StoreVersion.Tables[0].Rows[i]["Product_Model"].ToString().Trim();

                        P_Machine = _Machine_WMS;// 初始赋值机种名称（经过T字工位时可能会改变）

                        _Serial_Number = ds_01_StoreVersion.Tables[0].Rows[i]["Serial_Number"].ToString().Trim();

                        _Machine_Type = ds_01_StoreVersion.Tables[0].Rows[i]["BK03"].ToString().Trim();

                        bool falg = false;// 判定检查或者生产时间

                        VersionFalg = public_DS.Get02_Flag_Version(_IP, _Machine_WMS);// 判断是否有版本管理，减少查询次数

                        if (VersionFalg)
                        {
                            if (_Machine_Type != "PROAV")// 判定机种类种
                            {
                                #region 第 2 步 机型是否经过T字工位
                                P_Machine = public_DS.Get01_T_WorkStion(_IP, _Machine_WMS, _Serial_Number);  // 取生产实际用的机型名称//改变机型名称
                                if (P_Machine != "")
                                {
                                    T_Machine = _Machine_WMS;// 设置为T字机型，否则不经过T字工位 为空
                                }
                                else
                                {
                                    P_Machine = _Machine_WMS;
                                }
                                #endregion

                                if (P_Machine != "" && _Serial_Number != "")
                                {
                                    falg = false;
                                    _MovementNO = "";

                                    #region 第 3 步 获取机种、序列号、机芯号
                                    if (falg == false && _MovementNO == "")
                                    {
                                        _MovementNO = public_DS.Get03_1(_IP, P_Machine, _Serial_Number);
                                    }
                                    if (falg == false && _MovementNO == "")
                                    {
                                        _MovementNO = public_DS.Get03_2(_IP, P_Machine, _Serial_Number);
                                    }
                                    #endregion

                                    #region 第 4 步，对比查询生产过程中工位数据
                                    if (falg == false && _MovementNO != "" && _CheckTime == "")
                                    {
                                        _CheckTime = public_DS.Get04(_IP, P_Machine, _MovementNO);
                                        if (_CheckTime != "")
                                        {
                                            falg = true;
                                        }
                                    }
                                    if (falg == false && _MovementNO != "" && _CheckTime == "")
                                    {
                                        _CheckTime = public_DS.Get05(_IP, P_Machine, _MovementNO);
                                        if (_CheckTime != "")
                                        {
                                            falg = true;
                                        }
                                    }
                                    if (falg == false && _Serial_Number != "" && _CheckTime == "")
                                    {
                                        _CheckTime = public_DS.Get06(_IP, P_Machine, _Serial_Number);
                                        if (_CheckTime != "")
                                        {
                                            falg = true;
                                        }
                                    }
                                    #endregion
                                }
                            }
                            else
                            {
                                falg = false;
                                if (_CheckTime == "")
                                {
                                    _CheckTime = public_DS.Get07_PROAV(_IP, _Machine_WMS, _Serial_Number);//对比查询生产过程中工位数据
                                    if (_CheckTime != "")
                                    {
                                        falg = true;
                                    }
                                }
                            }

                            #region 第 5 步，取机种BOM中1个部品
                            _ProductNO_BOM = "";
                            if (falg)
                            {
                                if (T_Machine != "" && _ProductNO_BOM == "")
                                {
                                    _ProductNO_BOM = public_DS.Get08_BOM(_IP, T_Machine);
                                    falg = true;
                                }
                                else if (P_Machine != "" && _ProductNO_BOM == "")
                                {
                                    _ProductNO_BOM = public_DS.Get08_BOM(_IP, P_Machine);
                                    falg = true;
                                }
                            }
                            #endregion

                            #region 第 6 步，取部品最近的发料时间
                            if (_ProductNO_BOM != "" && _CheckTime != "" && _PKNO_Time == "")
                            {
                                _PKNO_Time = public_DS.Get09_PickingINFO(_IP, _ProductNO_BOM, _CheckTime);
                            }
                            #endregion

                            #region 第 7 步 对比版本基础表得到此序列号的版本号
                            if (_PKNO_Time != "")
                            {
                                if (T_Machine != "")
                                {
                                    _SetVersionNo = public_DS.Get10_Version(_IP, T_Machine, _PKNO_Time);
                                }
                                else
                                {
                                    _SetVersionNo = public_DS.Get10_Version(_IP, P_Machine, _PKNO_Time);
                                }
                            }
                            #endregion

                            #region 部分机种无法查询生产信息（赋值一个初始值版本号）
                            if (_SetVersionNo == "")
                            {
                                _SetVersionNo = "0";
                                P_Machine_ListStrDefault = P_Machine_ListStrDefault + i + ":[" + P_Machine + "-" + _Serial_Number + "]  ";
                            }
                            #endregion
                        }

                        #region 第 8 步 更新版本号
                        if (_SetVersionNo != "")
                        {
                            list.Add(" UPDATE [DB_WMSFIRST].[dbo].[T_Stock] SET BK12='" + _SetVersionNo + "' WHERE Product_Model='" + _Machine_WMS + "' AND Serial_Number ='%" + _Serial_Number + "'");
                            versionCount_Producted++;
                        }
                        else
                        {
                            P_Machine_ListStr = P_Machine_ListStr + i + ":[" + P_Machine + "-" + _Serial_Number + "]  ";
                        }
                        #endregion
                    }
                }
                if (list.Count > 0)
                {
                    if (SYDZ.WMS.DBUtility.DbHelperSQL.ExecuteSqlTran(list) == 0)
                    {
                        Message_Str = "版本号更新失败！";
                    }
                    else
                    {
                        if (versionCount_Producted == versionCount_Product)
                        {
                            Message_Str = "版本号更新完成！";
                        }
                        else if (versionCount_Producted < versionCount_Product)
                        {
                            Message_Str = "操作完成，有部分机种未能设置版本！";
                        }
                    }
                }
                ErrorLogLoad.ErrorLogInfo("////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////");
                ErrorLogLoad.ErrorLogInfo("VERSION NUMBER UPFATE|" + _UpdateStarTime1 + "/" + DateTime.Now + " Num:" + versionCount_Producted);

            }
            catch (Exception ex)
            {
                ErrorLogLoad.ErrorLogInfo(ex.Message.ToString());
                Message_Str = "系统操作异常！";
            }
        }
        #endregion

        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }
        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }
        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }


        public static List<T> ToDataList<T>(DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T s = Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageClass.error("字段[" + info.Name + "]转换出错, " + ex.Message);
                        }
                    }
                }
                list.Add(s);
            }
            return list;
        }
    }
    public class Entity_Version
    {
        public string ProductModel { get; set; }
        public string VersionNum { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
        public string CreatTime { get; set; }
    }
}
